package my.http;

import android.os.AsyncTask;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ffapp.rainmonitorcustom.basis.BasisApp;
import com.ffapp.rainmonitorcustom.basis.Constants;
import com.ffapp.rainmonitorcustom.bean.AlarmTypeBean;
import com.ffapp.rainmonitorcustom.bean.BaseMsgBean;
import com.ffapp.rainmonitorcustom.bean.BasicBeanStr;
import com.ffapp.rainmonitorcustom.bean.BasisBean;
import com.ffapp.rainmonitorcustom.bean.LoginBean;
import com.ffapp.rainmonitorcustom.util.MyUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.Executors;

import cz.msebera.android.httpclient.Header;
import my.LogUtil;
import my.MD5;
import my.SystemParamsUtils;
import my.TimeUtils;


public class HttpRestClient {
    public final static String tag = "HTTP";
    public final static boolean DEBUG = Constants.DEBUG;

    private static final String BASE_URL = "";

    private static AsyncHttpClient client = new AsyncHttpClient();
    private static final int TIME_OUT = 30 * 1000;

    static {
        client.setTimeout(TIME_OUT); // 设置链接超时，如果不设置，默认为10s
//       setHeader(client,params);
    }

    public static AsyncHttpClient getAsyncHttpClient() {
        return client;
    }

    public static void get(String url, RequestParams params,
                           AsyncHttpResponseHandler responseHandler) {
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
       setHeader(client,params);
        setCommentParams(params);
        client.get(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void get(String url, RequestParams params,
                           MyHttpListener mListener, int what) {
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
       setHeader(client,params);
        setCommentParams(params);
        client.get(getAbsoluteUrl(url), params, new MyHttpResposeHandler(
                mListener, what, null));
    }

    public static void get(String url, RequestParams params,
                           MyHttpListener mListener, int what, Class<?> class1) {
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
       setHeader(client,params);
        setCommentParams(params);
        client.get(getAbsoluteUrl(url), params, new MyHttpResposeHandler(
                mListener, what, class1));
    }

    public static void post(String url, RequestParams params,
                            AsyncHttpResponseHandler responseHandler) {
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
       setHeader(client,params);
        setCommentParams(params);
        client.post(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void post(String url, RequestParams params,
                            JsonHttpResponseHandler responseHandler) {
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
       setHeader(client,params);
        setCommentParams(params);
        client.post(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void post(String url, RequestParams params,
                            TextHttpResponseHandler responseHandler) {
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
       setHeader(client,params);
        setCommentParams(params);
        client.post(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void post(String url, RequestParams params,
                            MyHttpListener mListener, int what) {
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
       setHeader(client,params);
        setCommentParams(params);
        client.post(getAbsoluteUrl(url), params, new MyHttpResposeHandler(
                mListener, what, null));
    }

    public static AsyncHttpClient post(String url, RequestParams params,
                            MyHttpListener mListener, int what, Class<?> class1) {
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
       setHeader(client,params);
        setCommentParams(params);

        client.post(getAbsoluteUrl(url), params, new MyHttpResposeHandler(
                mListener, what, class1));

        return client;
    }

    public static void post(String url, RequestParams params,
                            MyHttpListener mListener, int what, int timeout, Class<?> class1) {
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
       setHeader(client,params);
        setCommentParams(params);
        client.setTimeout(timeout);
        client.post(getAbsoluteUrl(url), params, new MyHttpResposeHandler(
                mListener, what, class1));
    }

    public static void download(String url,
                                FileAsyncHttpResponseHandler mListener) {
//		setHeader(client);
//		setCommentParams(params);
        client.setMaxRetriesAndTimeout(0, TIME_OUT);
        client.get(getAbsoluteUrl(url), mListener);
    }

    private static String getAbsoluteUrl(String relativeUrl) {
        if (relativeUrl.startsWith("http")) {
            LogUtil.i(tag,relativeUrl);
            return relativeUrl;
        } else {

//			return Constants.getServerIp() + relativeUrl;
            LogUtil.i(tag,MyUtils.getServiceAPI()+relativeUrl);
            return MyUtils.getServiceAPI()+relativeUrl;
//            return relativeUrl;
        }
    }

    private static final String HEADER_PARAMS1 = "XF-API-app_id";
    private static final String HEADER_PARAMS2 = "XF-API-timestamp";
    private static final String HEADER_PARAMS3 = "XF-API-signature";
//    private static final String HEADER_HTTP_SourceID = "10001";//appid
    private static final String HEADER_HTTP_AuthKey = "NQVZR2SZZNKEF2J0JCEHZZLDYNJAMYXY6GCGSWMNIEKKNFWJ";

    private static void setHeader(AsyncHttpClient client,RequestParams params) {
//		client.addHeader("pwd", "test_password");
        // client.addHeader("", "");
             long time = new Date().getTime();
//        String time = TimeUtils.getCurrentTimeByFormat("yyyyMMddHHmmss");
//        client.addHeader(HEADER_PARAMS1, HEADER_HTTP_SourceID);
//        client.addHeader(HEADER_PARAMS1, MyUtils.getAppid());
//        client.addHeader(HEADER_PARAMS2, time + "");
//		 client.addHeader(
//		 HEADER_PARAMS3,
//		 MD5.getMD5ofStr(
//		 HEADER_HTTP_AuthKey + time + HEADER_HTTP_SourceID)
//		 .substring(0, 32));
        ArrayList<String> listP = new ArrayList<>();
        if(LoginBean.isLogin()){
            listP.add(LoginBean.getUserToken());
            String token = LoginBean.getUserToken();
            client.addHeader("accToken", LoginBean.getUserToken());
        }
        try {
            client.addHeader("user", URLEncoder.encode(MyUtils.getUser(),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        client.addHeader("timestamp", time+"");
        client.addHeader("os", "android"+SystemParamsUtils.getSystemReleaseVersion());
//        client.addHeader("XF-API-app_os", SystemParamsUtils.getPhoneModel());
        client.addHeader("version", SystemParamsUtils.getAppVersonName(BasisApp.mContext) + "");
//		client.addHeader("API-IMEI",""+SystemParamsUtils.getIMEI());
//		client.addHeader("API-DEVICE","API-TYPE");

//
//        listP.add(HEADER_HTTP_AuthKey);
//        listP.add(time);
//
//        if(params !=null){
//            String[] pramsStrs = params.toString().split("&");
//            for(String data:pramsStrs){
//                if(data.startsWith("file["))continue;
//                listP.add(data.substring(data.indexOf("=")+1));
//            }
//
//        }
//        client.addHeader(
//                HEADER_PARAMS3,getSecretStr(listP));


    }

    private static  String getSecretStr(ArrayList<String>  list) {
        String result = "";
        Collections.sort(list);
        StringBuilder builder = new StringBuilder();
        for(String data:list){
//            LogUtil.i(""+data);
            builder.append(data);
        }
//        LogUtil.i("字符串"+builder.toString());
            result = MD5.shaEncrypt(builder.toString());

            if(result.length()> 48){
                result = result.substring(0,48).toUpperCase();
            }
//            LogUtil.i("字符串sha1值"+result);
        return result;
    }

    public static  HashMap<String,String> getWebviewHeader() {
//		client.addHeader("pwd", "test_password");
        // client.addHeader("", "");
//		 long time = new Date().getTime();
        HashMap<String,String>  hashMap = new HashMap<>();
        String time = TimeUtils.getCurrentTimeByFormat("yyyyMMddHHmmss");
//        hashMap.put(HEADER_PARAMS1, HEADER_HTTP_SourceID);
        hashMap.put(HEADER_PARAMS1, MyUtils.getAppid());
        hashMap.put(HEADER_PARAMS2, time + "");
        String a =  SystemParamsUtils.getPhoneModel();
        String b =  SystemParamsUtils.getAppVersonName(BasisApp.mContext);
        hashMap.put("XF-API-app_type", "android");
        hashMap.put("XF-API-app_os", SystemParamsUtils.getPhoneModel());
        hashMap.put("XF-API-app_version", SystemParamsUtils.getAppVersonName(BasisApp.mContext) + "");

        ArrayList<String> listP = new ArrayList<>();
        listP.add(HEADER_HTTP_AuthKey);
        listP.add(time);
        if(LoginBean.isLogin()){
            listP.add(LoginBean.getUserToken());
            hashMap.put("XF-API-token", LoginBean.getUserToken());
        }
        hashMap.put(HEADER_PARAMS3,getSecretStr(listP));

        return  hashMap;

    }

    private static void setCommentParams(RequestParams params) {


        if (DEBUG) {
            LogUtil.i(tag, params.toString());
        }
        client.setTimeout(TIME_OUT);
        // if (params != null)
        // LogUtil.i("RequestParams--->" + params.toString());
        // if (!TextUtils.isEmpty(BasisApp.sAppId)
        // && !TextUtils.isEmpty(BasisApp.sAppId)) {
        // params.add("app_id", BasisApp.sAppId);
        // params.add("msisdn", BasisApp.sMsisdn);
        // }
    }

}

//class MyDownloadListener extends BinaryHttpResponseHandler {
//
//	@Override
//	public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
//		// TODO Auto-generated method stub
//
//	}
//
//	@Override
//	public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
//		// TODO Auto-generated method stub
//
//	}
//
//	@Override
//	public void onProgress(long bytesWritten, long totalSize) {
//		// TODO Auto-generated method stub
//		super.onProgress(bytesWritten, totalSize);
//	}
//
//}

class MyHttpResposeHandler extends AsyncHttpResponseHandler {
    private static String tag = "HTTP";
    int what = 0;
    MyHttpListener mListener;
    Class<?> clazz;

    public MyHttpResposeHandler() {
        super();
        // TODO Auto-generated constructor stub
    }

    public MyHttpResposeHandler(MyHttpListener mListener, int what,
                                Class<?> clazz) {
        super();
        this.what = what;
        this.mListener = mListener;
        this.clazz = clazz;

    }

    @Override
    public void onFailure(int statusCode, Header[] headers,
                          byte[] responseBody, Throwable arg3) {
        LogUtil.i(tag, "onFailure" + statusCode);
        if (mListener == null)
            return;
        Object object = parseResoposeBody(responseBody, clazz);
        if (object == null) {
            mListener.onFailure(what, null);
        } else {
            mListener.onFailure(what, object);
        }
//		mListener.onHttpFailure(what, arg3);
        mListener.onFinish(what);
    }

    //	Object object;
    @Override
    public void onSuccess(int statusCode, Header[] headers, final byte[] responseBody) {
        // TODO Auto-generated method stub
        LogUtil.i(tag, "onSuccess" + statusCode);
        if (mListener == null)
            return;
//		object = null;
        new AsyncTask<String, Integer, Object>() {

            @Override
            protected Object doInBackground(String... strings) {
                Object object = parseResoposeBody(responseBody, clazz);
                return object;
            }

            @Override
            protected void onPostExecute(Object object) {
                super.onPostExecute(object);
                if (object == null) {
                    mListener.onFailure(what, null);
                } else {
                    BasisBean bean = (BasisBean) object;
                    if (bean.isCodeOk()) {
                        mListener.onSuccess(what, object);
                    } else {
                        mListener.onFailure(what, object);
                    }
                }
                mListener.onFinish(what);
            }
        }.executeOnExecutor(Executors.newCachedThreadPool(), "");

        }


    @Override
    public void onCancel() {
        // TODO Auto-generated method stub
        LogUtil.i(tag, "onCancel");
        super.onCancel();
        if (mListener == null)
            return;
        mListener.onCancel(what);
        mListener.onFinish(what);
    }

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub
        super.onFinish();
        LogUtil.i(tag, "onFinish");
        if (mListener == null)
            return;
//		mListener.onFinish(what);
    }

    @Override
    public void onProgress(long bytesWritten, long totalSize) {
        // TODO Auto-generated method stub
        super.onProgress(bytesWritten, totalSize);
        if (mListener == null)
            return;
        mListener.onProgress(what, bytesWritten, totalSize);
    }

    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        if (mListener == null)
            return;
        mListener.onStart(what);
    }

    private static Object parseResoposeBody(byte[] responseBody, Class<?> clazz) {
        if (responseBody == null) return null;
        String result = new String(responseBody);
        LogUtil.i(tag, "" + result);
        if (TextUtils.isEmpty(result))
            return null;
        try {
            // result = StringUtil.decodeUnicode(result);
            MyBaseBean bean = JSON.parseObject(result, MyBaseBean.class);
            result =  JSON.toJSONString(bean,SerializerFeature.WriteNullStringAsEmpty);
            bean = JSON.parseObject(result, MyBaseBean.class);
//			MyBaseBean bean = JSON.parseObject(result, MyBaseBean.class);
            BasisBean resultBean;
            if (clazz == null) {
                resultBean = new BasisBean();
            } else if (!TextUtils.isEmpty(bean.getResultData())) {
                if (bean.getResultData().startsWith("[")) {
                    if (bean.getResultData().startsWith("[\"")) {
                        bean.setResultData("{\"list\":[]}");
                    } else {
                        bean.setResultData("{\"list\":" + bean.getResultData() + "}");
                    }
                }
                if (BasicBeanStr.class.isAssignableFrom(clazz)) {
//					JSONObject jsonObject = JSON.parseObject(bean.getResultData());
//					bean.setResultData("{\"msg\":\""+bean.getResultData()+"\"}");
                }
                if (BaseMsgBean.class.isAssignableFrom(clazz)) {
//					JSONObject jsonObject = JSON.parseObject(bean.getResultData());
                    bean.setResultData("{\"msg\":\"" + bean.getResultData() + "\"}");
                }
                 if (AlarmTypeBean.class.isAssignableFrom(clazz)) {
//					JSONObject jsonObject = JSON.parseObject(bean.getResultData());
                    bean.setResultData("{\"type\":" + bean.getResultData() + "}");
                    LogUtil.i(""+bean.getResultData());
                }
//
//				 if(!TextUtils.isEmpty(bean.getResultData()) && bean.getResultData().equals("数据为空")) {
//					bean.setResultData("{\"list\":[]}");
//				}

                if (!TextUtils.isEmpty(bean.getResultData()) && !bean.getResultData().startsWith("{")) {
                    resultBean = new BasisBean();
                    bean.setStatusCode(-1);
                } else {

                    resultBean = (BasisBean) JSON.parseObject(
                            bean.getResultData(), clazz);
                }
            } else if (bean.getResultData() == null
                    || bean.getResultData().equals("null")
                    || bean.getResultData().equals("{}")
                    || (bean.getResultData().length() == 0)) {
                resultBean = (BasisBean) clazz.newInstance();
            } else {
                resultBean = (BasisBean) JSON.parseObject(bean.getResultData(),
                        clazz);
            }
//            resultBean.setStatusCode(bean.getStatusCode());
            resultBean.setCode((bean.getCode()));
            resultBean.setStatusInfo(bean.getStatusInfo());
            resultBean.setResultData(bean.getResultData());
            resultBean.setApi_time(bean.getApi_time());
            resultBean.setRecordsTotal(bean.getRecordsTotal());
            return resultBean;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}